package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

@Slf4j
@RestControllerAdvice//标识为全局异常处理类
public class GlobalExceptionHandler {


    @ExceptionHandler(IllegalArgumentException.class)
    public JsonResult doHandler(IllegalArgumentException ex) {
        log.debug("IllegalArgumentException：" + ex.getMessage());
        String data = ex.getMessage();
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

//    @ExceptionHandler(RuntimeException.class)
//    public JsonResult doHandler(RuntimeException ex) {
//        log.debug("RuntimeException：" + ex.getMessage());
//        String data = ex.getMessage();
//        return new JsonResult(StatusCode.RUNTIME_ERROR, data);
//    }
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandler(MaxUploadSizeExceededException ex) {
        log.debug("MaxUploadSizeExceededException：" + ex.getMessage());
        String data = "上传文件大小超出限制";
        return new JsonResult(StatusCode.FILE_SIZE_ERROR, data);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandler(MethodArgumentNotValidException ex) {
        String data = ex.getBindingResult().getFieldError().getDefaultMessage();
        log.debug("MethodArgumentNotValidException：" + data);
        return  new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult doHandler(ConstraintViolationException ex) {
        String data = ex.getMessage().split(":")[1].trim();
        log.debug("ConstraintViolationException：" + data);
        return  new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

//    @ExceptionHandler(Throwable.class)//捕获所有异常,一般最后添加
//    public JsonResult doHandlerThrowable(Throwable throwable) {
//        String data = throwable.getMessage();
//        log.debug("捕获异常：" + data);
//        return  JsonResult.fail(data);
//    }
}
